import router, { createAsyncRouter, resetRouter } from '@/router'
import { ElMessage } from 'element-plus'
import useUserStore from './store/user'
import getPageTitle from './utils/getPageTitle'
import store from '@/store'
import auth from './utils/auth'
const whiteList = ['/login','/loginScan','/success'] // 检查登录态 白名单
let hasGetUserInfo = false;
let fullPath = ''
router.beforeEach(async (to, from, next) => {
	const userStore = useUserStore()
	// set page title
	document.title = getPageTitle(to.meta?.title || '')
	// determine whether the user has logged in
	const { token } = userStore
	if (token) {
		// 防止多次加载
		if (!hasGetUserInfo) {
			await store.dispatch('getrole')	// 生成后端返回的动态路由
			auth.init(store.state.menu.map(item => item.url))
			createAsyncRouter()
		}

		if (to.path === '/login') {
			next({ path: '/' }) // 已有登录态重定向至首页
		} else {
			const { name } = userStore
			if (name) {
				let to_status = false
				fullPath = to.fullPath
				if (!hasGetUserInfo) {
					// F5刷新页面后，再执行一次重定向
					next(fullPath)
					hasGetUserInfo = true
					return
				}
				if (to.fullPath.includes('/404')) {
					// 前往了非授权路由
					if (to_status == false) {
						ElMessage({
							message: '无权限访问',
							type: 'error'
						})
						return
					}
				}
				next()
			} else {
				try {
					// 获取用户信息
					await userStore.getInfo()
					next({ ...to, replace: true })
				} catch (err) {
					console.log(err)
					// 清除登录态
					await userStore.resetToken()
					ElMessage.error(err || '登录态异常')
					next(`/login`)
				}
			}
		}
	} else {
		hasGetUserInfo = false
		// 初始化路由
		resetRouter() // 清空路由
		// 未登录
		if (whiteList.indexOf(to.path) !== -1) {
			// 白名单直接跳转
			next()
		} else {
			// 其他页面未登录重定向回登录页面
			let official = localStorage.getItem('official')
			if(official){
				next(`login?official=${official}`)
			}else{
				next(`login`)
			}
			
		}
	}
	
})